﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NewFormatProject.Infrastructure.Atrributes;
using NewFormatProject.Infrastructure.Dto.Requests;
using NewFormatProject.Infrastructure.Dto.Requests.Objects;
using NewFormatProject.Infrastructure.Dto.Responses;
using NewFormatProject.Infrastructure.Tools;
using NewFormatProject.Server.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace NewFormatProject.Api.Admin.Controllers
{
    public class ToolsController : BaseController
    {
        private const long MaxFileSize = 2 * 1024 * 1024; // 2MB

        private bool IsFileSizeValid(IFormFile file)
        {
            return file.Length <= MaxFileSize;
        }
        private readonly List<string> _allowedExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".gif" };
        private readonly List<string> _allowedContentTypes = new List<string> { "image/jpeg", "image/png", "image/gif" };
        private readonly IUserServer _userServer;
        
        public ToolsController(IUserServer userServer)
        {
            _userServer = userServer;
        }

        private bool IsFileTypeValid(IFormFile file)
        {
            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            var contentType = file.ContentType.ToLowerInvariant();

            return _allowedExtensions.Contains(extension) && _allowedContentTypes.Contains(contentType);
        }

        /// <summary>
        /// 用户更换头像
        /// </summary>
        /// <param name="model">{file:file}</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [CheckLogin]
        public async Task<IActionResult> UserChangeAvatar([FromForm] RequestUploadDto model)
        {
            if (model.file == null || model.file.Length == 0)
            {
                return BadRequest("未选择文件");
            }

            if (!IsFileSizeValid(model.file))
            {
                return Ok(ResponseApiDto.Fail("文件大小超过限制"));
            }

            if (!IsFileTypeValid(model.file))
            {
                return Ok(ResponseApiDto.Fail("文件类型不符合要求"));
            }

            if (!string.IsNullOrEmpty(_user.UAvatar))
            {
                string oldAcatarPath = Path.Combine(Tools.GetMainProgramPath(), "wwwroot","Uploads","Images",_user.UId.ToString(), _user.UAvatar);
                // 检查文件是否存在
                if (System.IO.File.Exists(oldAcatarPath))
                {
                    // 删除文件
                    System.IO.File.Delete(oldAcatarPath);
                }
            }
            var fileName = Tools.Guid_2() + Path.GetExtension(model.file.FileName).ToLowerInvariant();
            var filePath = Path.Combine(Tools.GetMainProgramPath(), "wwwroot", "Uploads","Images", _user.UId.ToString(),fileName);

            // 确保uploads文件夹存在
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await model.file.CopyToAsync(stream);
            }
            _user.UAvatar = fileName;
            await _userServer.Update(_user);

            return Ok(ResponseApiDto.Success("上传成功",filePath));
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        
        public async Task<IActionResult> Upload([FromForm] RequestUploadDto model)
        {
            if (model.file == null || model.file.Length == 0)
            {
                return BadRequest("未选择文件");
            }

            if (!IsFileSizeValid(model.file))
            {
                return Ok(ResponseApiDto.Fail("文件大小超过限制"));
            }
            if (!IsFileTypeValid(model.file))
            {
                return Ok(ResponseApiDto.Fail("文件类型不符合要求"));
            }
            string fillName=Tools.Guid_2()+ Path.GetExtension(model.file.FileName).ToLowerInvariant();
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "Uploads", fillName);

            // 确保uploads文件夹存在
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await model.file.CopyToAsync(stream);
            }

            return Ok(ResponseApiDto.Success("上传成功", fillName));
        }
    }
}
